<template>
  <div class="wholesale-order-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>批发订单管理</h2>
      <p>管理批发订单，包括大宗商品订单、价格协商、批量发货等</p>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-card>
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item label="订单编号">
            <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
          </el-form-item>
          <el-form-item label="客户名称">
            <el-select v-model="searchForm.customerId" placeholder="请选择客户" clearable>
              <el-option
                v-for="customer in customers"
                :key="customer.id"
                :label="customer.name"
                :value="customer.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待审核" value="pending" />
              <el-option label="已审核" value="approved" />
              <el-option label="生产中" value="producing" />
              <el-option label="待发货" value="ready" />
              <el-option label="已发货" value="shipped" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item label="下单日期">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增订单
      </el-button>
      <el-button type="success" @click="handleBatchApprove" :disabled="!selectedOrders.length">
        <el-icon><Check /></el-icon>
        批量审核
      </el-button>
      <el-button type="warning" @click="handleExport">
        <el-icon><Download /></el-icon>
        导出数据
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单编号" width="150" fixed="left" />
        <el-table-column prop="customerName" label="客户名称" width="150" />
        <el-table-column prop="totalAmount" label="订单金额" width="120" sortable>
          <template #default="{ row }">
            <span class="amount">¥{{ row.totalAmount.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="商品数量" width="100" sortable />
        <el-table-column prop="status" label="订单状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderDate" label="下单日期" width="120" />
        <el-table-column prop="deliveryDate" label="交货日期" width="120" />
        <el-table-column prop="salesperson" label="销售员" width="100" />
        <el-table-column prop="remark" label="备注" width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)" v-if="row.status === 'pending'">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="success" @click="handleApprove(row)" v-if="row.status === 'pending'">
              <el-icon><Check /></el-icon>
              审核
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" v-if="row.status === 'pending'">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%" top="5vh">
      <OrderForm
        v-if="dialogVisible"
        :order-data="currentOrder"
        :mode="dialogMode"
        @save="handleSave"
        @cancel="handleCancel"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Check,
  Download,
  View,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import OrderForm from './components/OrderForm.vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogMode = ref('add') // add, edit, view
const currentOrder = ref(null)
const selectedOrders = ref([])

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  customerId: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 客户列表
const customers = ref([
  { id: 1, name: '华润万家' },
  { id: 2, name: '沃尔玛' },
  { id: 3, name: '家乐福' },
  { id: 4, name: '大润发' },
  { id: 5, name: '永辉超市' }
])

// 表格数据
const tableData = ref([
  {
    id: 1,
    orderNo: 'WO202401001',
    customerName: '华润万家',
    totalAmount: 158000,
    quantity: 500,
    status: 'pending',
    orderDate: '2024-01-15',
    deliveryDate: '2024-01-25',
    salesperson: '张三',
    remark: '春节备货订单'
  },
  {
    id: 2,
    orderNo: 'WO202401002',
    customerName: '沃尔玛',
    totalAmount: 235000,
    quantity: 800,
    status: 'approved',
    orderDate: '2024-01-16',
    deliveryDate: '2024-01-28',
    salesperson: '李四',
    remark: '促销活动商品'
  },
  {
    id: 3,
    orderNo: 'WO202401003',
    customerName: '家乐福',
    totalAmount: 89000,
    quantity: 300,
    status: 'producing',
    orderDate: '2024-01-17',
    deliveryDate: '2024-01-30',
    salesperson: '王五',
    remark: '定制包装要求'
  },
  {
    id: 4,
    orderNo: 'WO202401004',
    customerName: '大润发',
    totalAmount: 167000,
    quantity: 600,
    status: 'shipped',
    orderDate: '2024-01-18',
    deliveryDate: '2024-02-01',
    salesperson: '赵六',
    remark: '加急订单'
  },
  {
    id: 5,
    orderNo: 'WO202401005',
    customerName: '永辉超市',
    totalAmount: 198000,
    quantity: 750,
    status: 'completed',
    orderDate: '2024-01-19',
    deliveryDate: '2024-02-02',
    salesperson: '孙七',
    remark: '长期合作客户'
  }
])

// 计算属性
const filteredData = computed(() => {
  let data = [...tableData.value]
  
  if (searchForm.orderNo) {
    data = data.filter(item => item.orderNo.includes(searchForm.orderNo))
  }
  
  if (searchForm.customerId) {
    const customer = customers.value.find(c => c.id === searchForm.customerId)
    if (customer) {
      data = data.filter(item => item.customerName === customer.name)
    }
  }
  
  if (searchForm.status) {
    data = data.filter(item => item.status === searchForm.status)
  }
  
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    data = data.filter(item => {
      const orderDate = new Date(item.orderDate)
      const startDate = new Date(searchForm.dateRange[0])
      const endDate = new Date(searchForm.dateRange[1])
      return orderDate >= startDate && orderDate <= endDate
    })
  }
  
  return data
})

// 方法
const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    approved: 'info',
    producing: 'primary',
    ready: 'success',
    shipped: 'success',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已审核',
    producing: '生产中',
    ready: '待发货',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    customerId: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

const handleAdd = () => {
  dialogTitle.value = '新增批发订单'
  dialogMode.value = 'add'
  currentOrder.value = null
  dialogVisible.value = true
}

const handleView = (row) => {
  dialogTitle.value = '查看订单详情'
  dialogMode.value = 'view'
  currentOrder.value = { ...row }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑批发订单'
  dialogMode.value = 'edit'
  currentOrder.value = { ...row }
  dialogVisible.value = true
}

const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm('确认审核通过该订单？', '确认操作', {
      type: 'warning'
    })
    
    // 模拟API调用
    loading.value = true
    setTimeout(() => {
      const index = tableData.value.findIndex(item => item.id === row.id)
      if (index !== -1) {
        tableData.value[index].status = 'approved'
      }
      loading.value = false
      ElMessage.success('订单审核成功')
    }, 1000)
  } catch {
    // 用户取消操作
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该订单？删除后不可恢复！', '确认删除', {
      type: 'warning'
    })
    
    // 模拟API调用
    loading.value = true
    setTimeout(() => {
      const index = tableData.value.findIndex(item => item.id === row.id)
      if (index !== -1) {
        tableData.value.splice(index, 1)
        pagination.total--
      }
      loading.value = false
      ElMessage.success('订单删除成功')
    }, 1000)
  } catch {
    // 用户取消操作
  }
}

const handleBatchApprove = async () => {
  if (!selectedOrders.value.length) {
    ElMessage.warning('请选择要审核的订单')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确认批量审核选中的 ${selectedOrders.value.length} 个订单？`, '确认操作', {
      type: 'warning'
    })
    
    // 模拟API调用
    loading.value = true
    setTimeout(() => {
      selectedOrders.value.forEach(order => {
        const index = tableData.value.findIndex(item => item.id === order.id)
        if (index !== -1 && tableData.value[index].status === 'pending') {
          tableData.value[index].status = 'approved'
        }
      })
      selectedOrders.value = []
      loading.value = false
      ElMessage.success('批量审核成功')
    }, 1500)
  } catch {
    // 用户取消操作
  }
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

const handleSelectionChange = (selection) => {
  selectedOrders.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const handleSave = (orderData) => {
  // 模拟保存操作
  loading.value = true
  setTimeout(() => {
    if (dialogMode.value === 'add') {
      const newOrder = {
        ...orderData,
        id: Date.now(),
        orderNo: `WO${new Date().getFullYear()}${String(Date.now()).slice(-5)}`
      }
      tableData.value.unshift(newOrder)
      pagination.total++
      ElMessage.success('订单创建成功')
    } else if (dialogMode.value === 'edit') {
      const index = tableData.value.findIndex(item => item.id === orderData.id)
      if (index !== -1) {
        tableData.value[index] = { ...orderData }
      }
      ElMessage.success('订单更新成功')
    }
    
    loading.value = false
    dialogVisible.value = false
  }, 1000)
}

const handleCancel = () => {
  dialogVisible.value = false
}

const loadData = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    pagination.total = filteredData.value.length
    loading.value = false
  }, 500)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.wholesale-order-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.table-section {
  margin-bottom: 20px;
}

.amount {
  font-weight: 600;
  color: #E6A23C;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .wholesale-order-management {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .action-section {
    flex-direction: column;
  }
  
  .action-section .el-button {
    width: 100%;
  }
}
</style>